// 数据库操作日志切面模块
use rusqlite::{Connection, Result, types::{ToSqlOutput, Value, ValueRef}};
use std::fmt::Debug;
use std::time::Instant;

// 在Android环境中使用android_log模块
#[cfg(target_os = "android")]
use crate::android_log;

/// 格式化参数内容的辅助函数
fn format_param_content(param: &dyn rusqlite::ToSql) -> String {
    // 尝试将ToSql参数转换为可显示的字符串
    match param.to_sql() {
        Ok(output) => match output {
            ToSqlOutput::Owned(value) => match value {
                Value::Null => "NULL".to_string(),
                Value::Integer(i) => i.to_string(),
                Value::Real(r) => r.to_string(),
                Value::Text(s) => format!("'{}'", s),
                Value::Blob(b) => format!("BLOB[{} bytes]", b.len())
            },
            ToSqlOutput::Borrowed(value_ref) => match value_ref {
                ValueRef::Null => "NULL".to_string(),
                ValueRef::Integer(i) => i.to_string(),
                ValueRef::Real(r) => r.to_string(),
                ValueRef::Text(s) => format!("'{}'", String::from_utf8_lossy(s)),
                ValueRef::Blob(b) => format!("BLOB[{} bytes]", b.len())
            },
            _ => format!("未处理的ToSqlOutput类型"),
        },
        Err(_) => {
            // 如果无法转换，尝试使用类型信息
            let type_name = std::any::type_name_of_val(param);
            let display_name = match type_name.rsplit_once("::") {
                Some((_, last)) => last.to_string(),
                None => type_name.to_string()
            };
            format!("{}(无法转换显示)", display_name)
        }
    }
}

/// 数据库操作日志切面函数
/// 用于执行SQL查询并记录日志
pub fn execute_query<T, F>(_conn: &Connection, sql: &str, params: &[&dyn rusqlite::ToSql], f: F) -> Result<T>
where
    F: FnOnce() -> Result<T>,
    T: Debug + Send + Sync + 'static,
{
    // 记录开始时间
    let start_time = Instant::now();
    
    // 显示SQL语句
    #[cfg(target_os = "android")]
    android_log::debug("TauriDB", &format!("SQL: {}", sql));
    #[cfg(not(target_os = "android"))]
    println!("[数据库操作] SQL: {}", sql);
    
    // 显示参数内容
    #[cfg(target_os = "android")]
    android_log::debug("TauriDB", "参数列表:");
    #[cfg(not(target_os = "android"))]
    println!("[数据库操作] 参数列表:");
    
    for (i, param) in params.iter().enumerate() {
        // 尝试转换为常见类型并显示内容
        let param_content = format_param_content(param);
        #[cfg(target_os = "android")]
        android_log::debug("TauriDB", &format!("  参数 {}: {}", i, param_content));
        #[cfg(not(target_os = "android"))]
        println!("[数据库操作]   参数 {}: {}", i, param_content);
    }
    
    // 执行数据库操作
    let result = f();
    
    // 计算执行时间
    let duration = start_time.elapsed();
    
    match &result {
        Ok(value) => {
            // 对于查询操作，显示返回的数据
            if sql.trim_start().to_uppercase().starts_with("SELECT") {
                #[cfg(target_os = "android")]
                android_log::debug("TauriDB", &format!("查询结果: {:?}", value));
                #[cfg(not(target_os = "android"))]
                println!("[数据库操作] 查询结果: {:?}", value);
            }
            #[cfg(target_os = "android")]
            android_log::info("TauriDB", &format!("执行成功，耗时: {:?}", duration));
            #[cfg(not(target_os = "android"))]
            println!("[数据库操作] 执行成功，耗时: {:?}", duration);
        },
        Err(e) => {
            #[cfg(target_os = "android")]
            android_log::error("TauriDB", &format!("执行失败: {}", e));
            #[cfg(not(target_os = "android"))]
            println!("[数据库操作] 执行失败: {}", e);
        }
    }
    
    result
}

/// 简化的数据库执行函数，用于INSERT, UPDATE, DELETE等不返回数据的操作
pub fn execute_non_query(conn: &Connection, sql: &str, params: &[&dyn rusqlite::ToSql]) -> Result<usize> {
    execute_query(conn, sql, params, || conn.execute(sql, params))
}

/// 简化的数据库查询函数，用于单行查询
pub fn query_row<T, F>(conn: &Connection, sql: &str, params: &[&dyn rusqlite::ToSql], f: F) -> Result<T>
where
    F: FnOnce(&rusqlite::Row<'_>) -> Result<T>,
    T: Debug + Send + Sync + 'static,
{
    execute_query(conn, sql, params, || conn.query_row(sql, params, f))
}

/// 简化的数据库查询函数，用于多行查询
pub fn query_map<T, F>(conn: &Connection, sql: &str, params: &[&dyn rusqlite::ToSql], f: F) -> Result<Vec<T>>
where
    F: FnMut(&rusqlite::Row<'_>) -> Result<T>,
    T: Debug + Send + Sync + 'static,
{
    execute_query(conn, sql, params, || {
        let mut stmt = conn.prepare(sql)?;
        let results: Vec<T> = stmt.query_map(params, f)?.collect::<Result<_>>()?;
        Ok(results)
    })
}

/// 简化的数据库查询函数，用于获取单个值
pub fn query_scalar<T: rusqlite::types::FromSql + Debug + Send + Sync + 'static>(
    conn: &Connection, 
    sql: &str, 
    params: &[&dyn rusqlite::ToSql]
) -> Result<T> {
    query_row(conn, sql, params, |row| row.get(0))
}